namespace OpenWaves.HtmlEncoding
{
    public class TruncatingHtmlWriterDecorator : IHtmlWriter
    {
        private readonly IHtmlWriter inner;
        private int contentLength;
        private readonly int maxLength;

        public TruncatingHtmlWriterDecorator(IHtmlWriter inner, int maxLength)
        {
            this.inner = inner;
            this.maxLength = maxLength;
            contentLength = 0;
        }

        public void WriteText(string text)
        {
            if (contentLength + text.Length > maxLength)
            {
                var truncatedTextLength = maxLength - contentLength;
                contentLength += truncatedTextLength;
                inner.WriteText(text.Truncate(truncatedTextLength));
            }
            else
            {
                contentLength += text.Length;
                inner.WriteText(text);
            }
        }

        public void WriteTag(string tag)
        {
            inner.WriteTag(tag);
        }

        public override string ToString()
        {
            return inner.ToString();
        }
    }
}